<template>
  <div>
    <h1>品牌统计案例</h1>
    <table>
      <thead>
        <tr>
          <th>编号</th>
          <th>资产名称</th>
          <th>价格</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- // 1：循环渲染数据 -->
        <tr v-for="item in list"
            :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td>{{item.time}}</td>
          <td><a href="javascript:;"
               @click="delFn(item.id)">删除</a></td>
        </tr>
      </tbody>
    </table>
    <input type="text"
           placeholder="资产名称"
           v-model.trim="Sname">
    <input type="text"
           placeholder="资产价格"
           v-model="Sprice">
    <button @click="addFn">添加一件商品</button>
    <h3>总价格：{{sum}}</h3>
    <p>{{avgPrice}}</p>
  </div>
</template>

<script>
// 1: 渲染数据
// 2：添加一条数据(有输入框和价格)，点击按钮添加
// 3：点击删除一条数据
// 4：计算属性中统计所有书籍的总价格
// 5：过滤器中格式化日期时间
export default {
  data () {
    return {
      list: [
        {
          id: 1,
          name: '衣服',
          price: 122,
          time: 2021
        },
        {
          id: 2,
          name: '裤子',
          price: 132,
          time: 2021
        },
        {
          id: 3,
          name: '帽子',
          price: 162,
          time: 2021
        },
      ],
      Sname: '',
      Sprice: 0
    }
  },
  methods: {
    addFn () {
      if (this.Sname.length <= 0 || this.Sprice === 0) {
        alert('请按规则输入商品信息')
        return
      }
      let id = this.list.length + 1
      this.list.push({
        id: id,
        name: this.Sname,
        price: this.Sprice,
        time: new Date()
      })
    },
    delFn (id) {
      let index = this.list.findIndex(item => item.id === id)
      this.list.splice(index, 1)
    }
  },
  computed: {
    sum () {
      return this.list.reduce((item, val) => item += val.price, 0)
    },
    avgPrice () {
      return (this.sum / this.list.length).toFixed(2)
    }
  }
}
</script>

<style scoped>
table {
  /* border: 1px solid red; */
  width: 500px;
  text-align: center;
  padding: 0px;
  border-spacing: 0px;
}
thead {
  background-color: #ccc;
}
tbody tr td {
  border-collapse: collapse;
  border: 1px solid blue;
}
</style>